package cn.ithers.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.ithers.blog.dao.ArticleDao;
import cn.ithers.blog.domain.EsArticle;
import cn.ithers.blog.pojo.Article;
import cn.ithers.blog.repository.EsArticleRepository;
import cn.ithers.blog.service.IEsArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: zhanghuan
 * @date: 2020/10/26 12:26
 * @description:
 */

@Slf4j
@Service
public class EsArticleServiceImpl implements IEsArticleService {
    @Autowired
    private EsArticleRepository esArticleRepository;

    @Autowired
    private ArticleDao articleDao;


    /**
     * 导入所有文章数据到es
     *
     * @return
     */
    @Override
    public int importAll() {

        List<Article> all = articleDao.findAll();
        ArrayList<EsArticle> esArticleArrayList = new ArrayList<>();
        for (Article article : all) {
            esArticleArrayList.add(getArticleAll(article));
        }

        Iterable<EsArticle> esArticles = esArticleRepository.saveAll(esArticleArrayList);
        Iterator<EsArticle> iterator = esArticles.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        esArticleRepository.findAll();
        return result;

    }

    /**
     * 添加单篇文章
     * @param esArticle
     */
    public void add(EsArticle esArticle){
       esArticleRepository.save(esArticle);
    }

    /**
     * 根据id删除文章
     */
    @Override
    public void delete(String id) {
        esArticleRepository.deleteById(id);

    }



    /**
     * 批量删除文章
     */
    @Override
    public void delete(List<String> ids) {

    }

    /**
     * 根据关键字搜索标题或者内容
     */
    @Override
    public Page<EsArticle> search(String keyword, int page, int pageSize) {
        Pageable pageable = PageRequest.of(page, pageSize);
        return esArticleRepository.findByTitleOrContent(keyword, keyword, pageable);
    }

    /**
     * 根据关键字搜索标题或者内容复合查询
     */
    @Override
    public Page<EsArticle> search(String keyword, String id, String ArticleId, int page, int pageSize, int sort) {
        return null;
    }

    /**
     * 根据商品id推荐相关文章
     */
    @Override
    public Page<EsArticle> recommend(String id, int page, int pageSize) {
        return null;
    }

    /**
     * 解析
     *
     * @param article
     * @return
     */
    private EsArticle getArticleAll(Article article) {
        EsArticle esArticle = new EsArticle();
        BeanUtil.copyProperties(article, esArticle);
        return esArticle;
    }


}
